import Mock from 'mockjs'

// 延迟设置
Mock.setup({
  timeout: '300-600'
})

// 用户相关的mock数据
const users = [
  { id: 1, email: 'admin@example.com', password: 'password123', role: 'admin', nickname: '管理员' },
  { id: 2, email: 'user@example.com', password: 'user123', role: 'user', nickname: '普通用户' }
]

// 登录接口
Mock.mock('/api/login', 'post', (options) => {
  const { email, password } = JSON.parse(options.body)
  const user = users.find(u => u.email === email && u.password === password)
  
  if (user) {
    return {
      code: 200,
      message: '登录成功',
      data: {
        token: `mock-token-${user.id}`,
        user: {
          id: user.id,
          email: user.email,
          role: user.role,
          nickname: user.nickname
        }
      }
    }
  } else {
    return {
      code: 401,
      message: '邮箱或密码错误',
      data: null
    }
  }
})

// 用户信息接口
Mock.mock('/api/user/info', 'get', () => {
  // 通常这里应该从请求头获取token并验证
  // 这里简化处理，直接返回admin用户信息
  return {
    code: 200,
    message: '获取成功',
    data: {
      id: 1,
      email: 'admin@example.com',
      role: 'admin',
      nickname: '管理员',
      avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
    }
  }
})

// 登出接口
Mock.mock('/api/logout', 'post', () => {
  return {
    code: 200,
    message: '登出成功',
    data: null
  }
})

// 注册接口
Mock.mock('/api/register', 'post', (options) => {
  const { email, password } = JSON.parse(options.body)
  
  // 检查邮箱是否已被注册
  if (users.some(u => u.email === email)) {
    return {
      code: 400,
      message: '该邮箱已被注册',
      data: null
    }
  }
  
  // 模拟添加新用户
  const newUser = {
    id: users.length + 1,
    email,
    password,
    role: 'user',
    nickname: `用户${users.length + 1}`
  }
  
  users.push(newUser)
  
  return {
    code: 200,
    message: '注册成功',
    data: {
      id: newUser.id,
      email: newUser.email,
      role: newUser.role,
      nickname: newUser.nickname
    }
  }
})

export default Mock 